#include <iostream>
#include "euler.h"

BEGIN_PROBLEM(327, solve_problem_327)
	PROBLEM_TITLE("Rooms of Doom")
	PROBLEM_ANSWER("34315549139516")
	PROBLEM_DIFFICULTY(1)
	PROBLEM_FUN_LEVEL(3)
	PROBLEM_TIME_COMPLEXITY("CR")
	PROBLEM_SPACE_COMPLEXITY("1")
END_PROBLEM()

static long long N(long long k, int C)
{
	if (k + 1 <= C)
	{
		return (k + 1);
	}
	else
	{
		long long r = (k - 2) / (C - 2);
		long long n = k + 2*r + 1;
		return n;
	}
}

static long long M(int C, int R)
{
	long long m = 1;
	while (R-- > 0)
	{
		m = N(m, C);
	}
	return m;
}

static long long sum_M(int C1, int C2, int R)
{
	long long sum = 0;
	for (int C = C1; C <= C2; C++)
	{
		//std::cout << "M(" << C << "," << R << ") = " << M(C, R) << std::endl;
		sum += M(C, R);
	}
	return sum;
}

static void solve_problem_327()
{
#if 0
	std::cout << "M(3,6) = " << M(3,6) << std::endl;
	std::cout << "M(4,6) = " << M(4,6) << std::endl;
	std::cout << "Sum M(3..10, 10) = " << sum_M(3,10,10) << std::endl;
	std::cout << "Sum M(3..40, 30) = " << sum_M(3,40,30) << std::endl;
#else
	std::cout << sum_M(3,40,30) << std::endl;
#endif
}
